﻿using System.Diagnostics;
using System.Threading;
using System.Collections;
using System.IO;

namespace AudioBook.AudioManagement.Util
{
    public class AudioBookUtility
    {
        public static ArrayList Split(string sourceFile, string desFolder, int splitTime)
        {
            string strMp3SpltFile = string.Empty;

            AudioCore.Common.AppConfigUtils.GetString(AudioCore.Common.Constant.ConfigKey.MP3_CUTTER, ref strMp3SpltFile);

            string strSrcFolder = sourceFile.Substring(0, sourceFile.LastIndexOf('\\'));
            string strBaseFileName = sourceFile.Substring(0, sourceFile.LastIndexOf('.'));
            string strTime = (splitTime / 60).ToString() + "." + (splitTime % 60).ToString();
            Process p;

            ProcessStartInfo prcMp3Splt = new ProcessStartInfo();
            prcMp3Splt.FileName = strMp3SpltFile;
            prcMp3Splt.Arguments = string.Format("\"{0}\" -o @f_@n -t {1} -d \"{2}\"", sourceFile, strTime, strSrcFolder);
            prcMp3Splt.WindowStyle = ProcessWindowStyle.Hidden;
            p = Process.Start(prcMp3Splt);
            p.WaitForExit();

            ArrayList arrResult = new ArrayList();
            int i = 1;
            while (true)
            {
                string strSubFile = strBaseFileName + "_" + i.ToString() + AudioCore.Common.Constant.AUDIO_EXTENSION;
                string strSubFile2 = strBaseFileName + "_0" + i.ToString() + AudioCore.Common.Constant.AUDIO_EXTENSION;
                string strSubFile3 = strBaseFileName + "_00" + i.ToString() + AudioCore.Common.Constant.AUDIO_EXTENSION;
                if (File.Exists(strSubFile2))
                {
                    arrResult.Add(strSubFile2);
                }
                else if (File.Exists(strSubFile))
                {
                    arrResult.Add(strSubFile);
                }
                else if (File.Exists(strSubFile3))
                {
                    arrResult.Add(strSubFile3);
                }
                else
                {
                    break;
                }
                i++;
            }
            return arrResult;
        }
    }
}
